package com.itstudio.portal.config;

import com.itstudio.portal.filter.JwtAuthorizeFilter;
import com.itstudio.portal.handle.AccessDeniedFilter;
import com.itstudio.portal.handle.AuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableGlobalMethodSecurity(prePostEnabled=true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AccessDeniedFilter accessDeniedFilter;

    @Autowired
    AuthenticationFilter authenticationFilter;

    @Autowired
    JwtAuthorizeFilter jwtAuthorizeFilter;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(conf -> conf
                        .antMatchers("/api/user/logout", "/api/user/getUserById/**", "/api/auth/**", "api/common/upload",
                                "/api/common/uploads","/api/project/add" ,"/api/project/update", "/api/project/delete/**",
                                "/api/news/addNews", "/api/news/updateNews" ,"/api/news/deleteNews/**").authenticated()
                        .anyRequest().permitAll())
                .sessionManagement(conf -> conf.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .exceptionHandling(conf -> conf.authenticationEntryPoint(authenticationFilter)
                        .accessDeniedHandler(accessDeniedFilter));

        http.addFilterBefore(jwtAuthorizeFilter, UsernamePasswordAuthenticationFilter.class);

        http.formLogin().disable();
        http.logout().disable();
        http.cors();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
